<template>
  <div class="card table-wrap">
    <div class="table-header">
      <slot name="tableHeader"></slot>
    </div>
    <el-table
      ref="tableRef"
      :id="uuid"
      v-loading="loading"
      :data="processTableData"
      border
      v-bind="$attrs"
      :rowKey>
      <template v-for="item in columns" :key="item">
        <!-- 判断条件如果有内置的类型 -->
        <el-table-column v-if="item.type && COLUMN_TYPE.includes(item.type)" v-bind="item" />
        <template v-else v-for="slot in Object.keys($slots)" :key="slot">
          <TableColumn :column="item" />
        </template>
      </template>
    </el-table>
    <Pagination
      v-if="pagination"
      :pagination="pageControl"
      :handleSizeChange="handleSizeChange"
      :handleCurrentChange="handleCurrentChange" />
  </div>
</template>

<script setup name="ProTable">
import { ref, onMounted, computed } from 'vue';
import useTable from './hooks';
import { generateUUID } from '@/utils';
import { COLUMN_TYPE } from './config';
import Pagination from './Pagination.vue';
import TableColumn from './TableColumn.vue';

const props = defineProps({
  columns: {
    type: Array,
    required: true,
    default: () => []
  },
  data: {
    type: Array,
    default: () => []
  },
  rowKey: {
    type: String,
    default: 'id'
  },
  pagination: {
    type: Boolean,
    default: true
  },
  requestAuto: {
    type: Boolean,
    default: true
  },
  initParams: {
    type: Object,
    default: () => {}
  },
  request: {
    type: Function,
    default: () => {}
  },
  dataCallBack: {
    type: Function,
    default: () => {}
  }
});

const uuid = ref('id-' + generateUUID());

const { loading, tableData, getTableData, pageControl, handleSizeChange, handleCurrentChange } =
  useTable(props.request, props.dataCallBack);

onMounted(() => {
  props.request && props.requestAuto && getTableData();
});

const processTableData = computed(() => {
  // 优先使用静态数据
  if (props.data.length) {
    return props.data;
  }

  return tableData.value || [];
});
</script>
